#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>

//4.0 控制台打印错误信息, fmt必须是双引号括起来的宏
#define CERR(fmt, ...) \
    fprintf(stderr,"[%s:%s:%d][error %d:%s]" fmt "\r\n",\
         __FILE__, __func__, __LINE__, errno, strerror(errno),##__VA_ARGS__)

//4.1 控制台打印错误信息并退出, t同样fmt必须是 ""括起来的字符串常量
#define CERR_EXIT(fmt,...) \
    CERR(fmt,##__VA_ARGS__),exit(EXIT_FAILURE)

//4.3 if 的 代码检测
#define IF_CHECK(code)    \
    if((code) < 0) \
        CERR_EXIT(#code)

//待拼接的字符串
#define _STR_HTTP_1 "1#1111#18303660110#123456\r\n"

#define _NET_ "127.0.0.1"
//#define _NET_ "123.57.35.104"

// 简单请求一下
int main(int argc, char* argv[])
{
    char buf[1024];
    
    

  	while(1)
	{ 
		int sfd;
		IF_CHECK(sfd = socket(AF_INET, SOCK_STREAM, 0));
		struct sockaddr_in saddr = { AF_INET };
		saddr.sin_port = htons(8888);
		saddr.sin_addr.s_addr = inet_addr(_NET_);

		IF_CHECK(connect(sfd, (struct sockaddr*)&saddr, sizeof(saddr)));
		
		const char chOpt=1;
		setsockopt(sfd,IPPROTO_TCP,TCP_NODELAY,&chOpt,sizeof(char));   
		//开始发送请求
		//strcpy(buf, _STR_HTTP_1);

		memset(buf,0,sizeof(buf));
		scanf("%s",buf);
		int ret = send(sfd, buf, strlen(buf),0);
		
		printf("%d-%s\n",ret,buf);
		fflush(fdopen(sfd,"r+"));
		//读取所有内容
		sleep(1);
		memset(buf,0,sizeof(buf));
		char c;
		char *tp = buf;
		int i = 0;
		#if 0
		while(1)
		{
			if(read(sfd, &c, 1) <= 0) 
				break;
			if(c == '\r'){
				if(recv(sfd, &c, 1, MSG_PEEK)>0 && c == '\n')
					read(sfd, &c, 1);
				else
					*tp++ = '\n';
				break;
			}
			*tp++ = c;
			i++;
		}
		*tp = '\0';
		printf("%d--%s\n",i,buf);
		#endif
		#if 1
		i = recv(sfd,buf,100,0);
		printf("%d--%s\n",i,buf);
		#endif
	}
    return 0;
}
